package com.example.demo.loader;

import com.sun.tools.javac.file.JavacFileManager;
import com.sun.tools.javac.util.Context;
import com.sun.tools.javac.util.ListBuffer;

import java.io.File;
import java.lang.reflect.Constructor;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.charset.Charset;

/**
 * java 文件管理器 主要用来 重新定义class loader
 */
public class SpringJavaFileManager extends JavacFileManager {

	public SpringJavaFileManager(Context context, boolean b, Charset charset) {
		super(context, b, charset);
	}

	@Override
	public ClassLoader getClassLoader(Location location) {
		nullCheck(location);
		Iterable<?> var2 = this.getLocation(location);
		if (var2 == null) {
			return null;
		} else {
			ListBuffer<URL> var3 = new ListBuffer<>();
			for (Object o : var2) {
				File var5 = (File) o;
				try {
					var3.append(var5.toURI().toURL());
				} catch (MalformedURLException var7) {
					throw new AssertionError(var7);
				}
			}
			return this.getClassLoader((URL[]) var3.toArray(new URL[0]));
		}
	}

	protected ClassLoader getClassLoader(URL[] var1) {
		ClassLoader var2 = this.getClass().getClassLoader();
		try {
			Class<?> loaderClass = Class.forName("org.springframework.boot.loader.LaunchedURLClassLoader");
			Class<?>[] var4 = new Class[]{URL[].class, ClassLoader.class};
			Constructor<?> var5 = loaderClass.getConstructor(var4);
			return (ClassLoader) var5.newInstance(var1, var2);
		} catch (Throwable var6) {
			var6.getStackTrace();
		}
		return new URLClassLoader(var1, var2);
	}
}
